﻿using System;
using System.IO;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;

namespace DataAccessObject.Hibernate
{
    /// <summary>
    /// 静态类 为单独线程提供NHibernate会话支持
    /// current_session_context_class
    /// thread_static
    /// </summary>
    public class NHThreadSessionFactory : INHSessionFactory
    {
        private readonly ISessionFactory sessionFactory;

        #region 初始化 SessionFactory
        public NHThreadSessionFactory()
        {
            Configuration config = new NHibernate.Cfg.Configuration().Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                @"bin\Hibernate\Config\Hibernate.cfg.xml"));
            sessionFactory = config.SetProperty("current_session_context_class", "thread_static").BuildSessionFactory();
        }
        #endregion

        /// <summary>
        /// 获得当前上下文的 Session
        /// </summary>
        /// <returns></returns>
        public ISession GetCurrentSession()
        {
            if (!CurrentSessionContext.HasBind(sessionFactory))
            {
                ISession session = sessionFactory.OpenSession();
                CurrentSessionContext.Bind(session);
                return session;
            }
            else
            {
                return sessionFactory.GetCurrentSession();
            }
        }

        public void BindContext()
        {
            if (!CurrentSessionContext.HasBind(sessionFactory))
            {
                CurrentSessionContext.Bind(sessionFactory.GetCurrentSession());
            }
        }

        public void UnBindContext()
        {
            if (CurrentSessionContext.HasBind(sessionFactory))
            {
                CurrentSessionContext.Unbind(sessionFactory);
            }
        }

    }
}
